package com.ma.aspect;



import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * @author 马永强
 */

//@Aspect:作用是把当前类标识为一个切面供容器读取

@Aspect
@Component
public class LogAspect {

    //this.getClass() 就是返回当前对象的运行时类。
    //Logger.getLogger(this.getClass())得到一个Logger对象，这个Logger将监视this.getClass()这个运行时类，
    //这个运行时类里面你可能创建了log.info(""), log.debug("")，……等语句，
    // 那么这些语句就会根据你预先定义的Logger级别来输出你的日志。就跟你写System.out.print("")一样，不同的是Logger可以根据需要按级别进行日志输出控制。

    public final Logger logger = LoggerFactory.getLogger(this.getClass());

    // @Pointcut：Pointcut是植入Advice的触发条件

    @Pointcut("execution(* com.ma.web.*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + '.' + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
        logger.info("Request : {}",requestLog);
    }
    @After("log()")
    public void doAfter(){
        //logger.info("--------doAfter----------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("Result : {}  ",result);
    }

    //内部类，指定返回参数
    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
